/**
 * http://git.oschina.net/hbbcs/bootStrap-addTabs
 * Created by joe on 2015-12-19.
 * Modified by FastAdmin and PGcao
 */

(function ($) {

    $.fn.addtabs = function (options) {
        var obj = $(this);

        options = $.extend({
            content: '', //直接指定所有页面TABS内容
            close: true, //是否可以关闭
            monitor: 'body', //监视的区域
            nav: '.nav-addtabs',
            tab: '.tab-addtabs',
            iframeUse: true, //使用iframe还是ajax
            simple: false, //是否启用简洁模式，简洁模式下将不启用nav和tab
            iframeHeight: $(window).height() - 50, //固定TAB中IFRAME高度,根据需要自己修改
            iframeForceRefresh: false, //点击后强制加载对应的iframe
            iframeForceRefreshTable: false, //点击后强制刷新对应的iframe中的table
            contextmenu: true,//是否使用右键菜单
            local: {
                'refreshLabel': '刷新此标签',
                'closeThisLabel': '关闭此标签',
                'closeOtherLabel': '关闭其他标签',
                'closeLeftLabel': '关闭左侧标签',
                'closeRightLabel': '关闭右侧标签',
                'closeAllLabel': '关闭全部标签'
            },

            callback: function () {
                //关闭后回调函数
            }
        }, options || {});

        var navobj = $(options.nav);
        var tabobj = $(options.tab);

        options.contextmenu && navobj.parent().bind('contextmenu',function(e){
            return false; 
        });

        // 防止sessionStorage被修改
        window.addEventListener('storage', function(e) {
            this.sessionStorage.setItem(e.key, e.oldValue);
        });

        // 记忆多标签(获取标签数据) PGCAO
        var addtabs_list = sessionStorage.getItem("addtabs_list");
            addtabs_list = addtabs_list && JSON.parse(addtabs_list) || {};

        if (history.pushState) {
            //浏览器前进后退事件
            $(window).on("popstate", function (e) {
                var state = e.originalEvent.state;
                if (state) {
                    $("a[addtabs=" + state.id + "]", options.monitor).data("pushstate", true).trigger("click");
                }
            });
        }

        var clickTimer; // 处理事件防抖 PGCAO
        $(options.monitor).on('click', '[addtabs]', function (e) {
            var that = this;
            if ($(that).attr('url').indexOf("javascript:") !== 0) {
                if ($(that).is("a")) {
                    e.preventDefault();
                }
                clearTimeout(clickTimer);
                clickTimer = setTimeout(function(){
                    var id = $(that).attr('addtabs');
                    var title = $(that).attr('title') ? $(that).attr('title') : $.trim($(that).text());
                    var url = $(that).attr('url');
                    var content = options.content ? options.content : $(that).attr('content');
                    var ajax = $(that).attr('ajax') === '1' || $(that).attr('ajax') === 'true';
                    var state = ({
                        url: url, title: title, id: id, content: content, ajax: ajax
                    });

                    document.title = title;
                    if (history.pushState && !$(that).data("pushstate")) {
                        var pushurl = url.indexOf("ref=addtabs") === -1 ? (url + (url.indexOf("?") > -1 ? "&" : "?") + "ref=addtabs") : url;
                        try {
                            window.history.pushState(state, title, pushurl);
                        } catch (e) {

                        }
                    }
                    $(that).data("pushstate", null);
                    
                    // 优化多标签的图标元素 PGcao 2024-07-26
                    var titleIcon = $(that).find('i').eq(0), titleText = $(that).find('span').eq(0);
                    var titleHtml = (titleIcon.length ? titleIcon[0].outerHTML : '<i class="fa fa-question"></i>') + ' <span>' + (titleText.length ? titleText.text() : title) + '</span>';

                    _add.call(that, {
                        id: id,
                        title: titleHtml,
                        content: content,
                        url: url,
                        ajax: ajax
                    });
                }, 200);
            }
        });

        $(window).resize(function () {
            if (typeof options.nav === 'object') {
                var siblingsWidth = 0;
                navobj.siblings().each(function () {
                    siblingsWidth += $(this).outerWidth();
                });
                navobj.width(navobj.parent().width() - siblingsWidth);
            } else {
                $("#nav").width($("#header").find("> .navbar").width() - $(".sidebar-toggle").outerWidth() - $(".navbar-custom-menu").outerWidth() - 20);
            }
            _drop();
        });

        var _drop = function () {
            navobj.refreshAddtabs();
        };

        // 记忆多标签(处理标签内容) PGCAO
        var _addContent = function(conitem, opts){
            if(!conitem.hasClass('tab-pane')){
                conitem.addClass('tab-pane').css('opacity', 0);

                var url = opts.url;
                url += (opts.url.indexOf("?") > -1 ? "&addtabs=1" : "?addtabs=1");

                //是否指定TAB内容
                if (opts.content) {
                    conitem.append(opts.content);
                    conitem.animate({opacity: 1}, 500);
                } else if (options.iframeUse && !opts.ajax) {//没有内容，使用IFRAME打开链接
                    var loadIndex = Layer.load(2);
                    var height = options.iframeHeight;
                    var iframe = $('<iframe src="' + url + '" width="100%" height="' + height + '" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling-x="no" scrolling-y="auto" allowtransparency="yes"></iframe>');
                    iframe.on('load', function(){                        
                        loadIndex && setTimeout(function(){
                            Layer.close(loadIndex);
                            loadIndex = null;
                            conitem.animate({opacity: 1}, 500);
                        }, 100);
                    });
                    conitem.append(iframe);
                } else {
                    $.get(url, function (data) {
                        conitem.append(data);
                        conitem.animate({opacity: 1}, 500);
                    });
                }
            }
        }

        var _add = function (opts, initialization) {
            // id title url content ajax in opts
            if(!/^\d+$/.test(opts.id) || !opts.title){
                return;
            }

            var id, tabid, conid;
            id = opts.id;
            tabid = 'tab_' + opts.id;
            conid = 'con_' + opts.id;

            if (options.simple) {
                navobj.find("[role='presentation']").remove();
                tabobj.find("[role='tabpanel']").remove();
            }

            var tabitem = $('#' + tabid, navobj);
            var conitem = $('#' + conid, tabobj);

            if(!initialization){
                navobj.find("[role='presentation']").removeClass('active');
                tabobj.find("[role='tabpanel']").removeClass('active');
            }

            //如果TAB不存在，创建一个新的TAB
            if (tabitem.length === 0) {
                //创建新TAB的title
                tabitem = $('<li role="presentation" id="' + tabid + '"><a href="#' + conid + '" node-id="' + opts.id + '" aria-controls="' + id + '" role="tab" data-toggle="tab">' + opts.title + '</a></li>');
                //是否允许关闭
                if (options.close && $("li", navobj).length > 0) {
                    tabitem.append(' <i class="close-tab fa fa-remove"></i>');
                }
                if (conitem.length === 0) {
                    //创建新TAB的内容, 去掉样式，改由记忆多标签(处理标签内容)处理 PGCAO
                    conitem = $('<div role="tabpanel" id="' + conid + '"></div>');

                    //记忆多标签(初始化时不处理内容) PGCAO
                    !initialization && _addContent(conitem, opts);
                    
                    tabobj.append(conitem);
                }

                if (!options.simple) {
                    //加入TABS
                    if ($('.tabdrop li', navobj).length > 0) {
                        $('.tabdrop ul', navobj).append(tabitem);
                    } else {
                        navobj.append(tabitem);
                    }
                }

                addtabs_list[id] = opts;
                sessionStorage.setItem("addtabs_list", JSON.stringify(addtabs_list));

            } else {
                //记忆多标签(重新处理一次内容) PGCAO
                if (conitem.length === 0) {
                    conitem = $('<div role="tabpanel" id="' + conid + '"></div>');
                    tabobj.append(conitem);
                }

                _addContent(conitem, opts);

                if(!initialization){
                    //强制刷新iframe
                    if (options.iframeForceRefresh) {
                        $("#" + conid + " iframe").attr('src', function (i, val) {
                            return val;
                        });
                    } else if (options.iframeForceRefreshTable) {
                        try {
                            //检测iframe中是否存在刷新按钮
                            if ($("#" + conid + " iframe").contents().find(".btn-refresh:not([data-force-refresh=false])").length > 0) {
                                $("#" + conid + " iframe")[0].contentWindow.$(".btn-refresh:not([data-force-refresh=false])").trigger("click");
                            }
                        } catch (e) {

                        }
                    }
                }
            }
            
            if(!initialization){
                sessionStorage.setItem("addtabs", $(this).prop('outerHTML'));
                //激活TAB
                tabitem.addClass('active');
                conitem.addClass("active");
            }

            _drop();
        };

        var _close = function (id) {
            var tabid = 'tab_' + id;
            var conid = 'con_' + id;
            var tabitem = $('#' + tabid, navobj);
            var conitem = $('#' + conid, tabobj);
            //如果关闭的是当前激活的TAB，激活他的前一个TAB
            if (obj.find("li.active").not('.tabdrop').attr('id') === tabid) {
                var prev = tabitem.prev().not(".tabdrop");
                var next = tabitem.next().not(".tabdrop");
                if (prev.length > 0) {
                    prev.find('a').trigger("click");
                } else if (next.length > 0) {
                    next.find('a').trigger("click");
                } else {
                    $(">li:not(.tabdrop):last > a", navobj).trigger('click');
                }
            }

            if(addtabs_list[id]){
                delete addtabs_list[id];
                sessionStorage.setItem("addtabs_list", JSON.stringify(addtabs_list));
            }

            //关闭TAB
            tabitem.remove();
            conitem.remove();
            
            _drop();

            options.callback();
        };

        //记忆多标签(弃用原双击事件) PGCAO
        // navobj.on('dblclick', 'li[role=presentation]', function () {
        //     $(this).find(".close-tab").trigger("click");
        //     return false;
        // });
        navobj.on('click', 'li[role=presentation]', function () {
            var that = this;
            clearTimeout(clickTimer);
            clickTimer = setTimeout(function(){
                $("a[addtabs=" + $("a", that).attr("node-id") + "]").trigger("click");
            }, 100);
            return false;
        });
        navobj.on('click', '.close-tab', function () {
            var id = $(this).prev("a").attr("aria-controls");
            _close(id);
            return false;
        });

var _createMenu = function (right, icon, text) {
    return $('<li>').append($('<a>', {
        'data-operate': right
    }).append(
        $('<i>', {'class': icon, 'style': 'margin-right:4px;'})
    ).append(text));
};
var mouseleaveTimer = null, isMouseleave = true, _menu = function (id, e, obj) {
    var menuID = 'navTabsMenu';
    var dropdown = $(".tabdrop", navobj);

    $('body').find('#'+menuID).remove();

    var refresh = e.attr('id') ? _createMenu('refresh', 'fa fa-refresh fa-fw', options.local.refreshLabel).on('click', function(){
        var id = $(this).parent().attr("aria-controls");
        if(!$("#tab_" + id, navobj).hasClass('active')){
            $("a[addtabs=" + id + "]").trigger("click");
        }else{
            $("#con_" + id + " iframe").attr('src', function (i, val) {
                return val;
            });
        }
    }) : '';
    var remove = e.attr('id') && !e.hasClass('fixetab') ? _createMenu('remove', 'fa fa-close fa-fw', options.local.closeThisLabel).on('click', function(){
        _close($(this).parent().attr("aria-controls"));
    }) : '';
    var removeOther = e.attr('id') && !e.hasClass('fixetab') ? _createMenu('remove-circle', 'fa fa-window-close-o fa-fw', options.local.closeOtherLabel).on('click', function(){
        var tab_id = 'tab_'+$(this).parent().attr("aria-controls");
        e.parent().find("li[role='presentation']").each(function () {
            if ($(this).attr('id') == tab_id) {
                return;
            }
            if ($(this).find(".close-tab").length > 0) {
                $(this).find(".close-tab").trigger("click");
            }
        });
    }) : '';
    var removeAll = e.attr('id') && e.hasClass('fixetab') ? _createMenu('remove-circle', 'fa fa-power-off fa-fw', options.local.closeAllLabel).on('click', function(){
        e.parent().find("li[role='presentation']").each(function () {
            if ($(this).find(".close-tab").length > 0) {
                $(this).find(".close-tab").trigger("click");
            }
        });
    }) : '';
    var isDropdownLI = dropdown.find('ul>li').length > 0;
    var left = e.prev('li').attr('id') && !e.prev('li').hasClass('fixetab') || isDropdownLI ? _createMenu('remove-left', 'fa fa-chevron-left fa-fw', options.local.closeLeftLabel).on('click', function(){
        var tab_id = 'tab_'+$(this).parent().attr("aria-controls");
        $('#' + tab_id).prevUntil().each(function () {
            var id = $(this).attr('id');
            if (id && !$(this).hasClass('fixetab') && id != tab_id) {
                $(this).find(".close-tab").trigger("click");
            }
        });
    }) : '';
    isDropdownLI = isDropdownLI && !e.parent().hasClass('dropdown-menu');
    var right = e.attr('id') && !e.hasClass('fixetab') && (e.next('li').attr('id') || isDropdownLI) ? _createMenu('remove-right', 'fa fa-chevron-right fa-fw', options.local.closeRightLabel).on('click', function(){
        var tab_id = 'tab_'+$(this).parent().attr("aria-controls");
        $('#' + tab_id).nextUntil().each(function () {
            var id = $(this).attr('id');
            if (id && id != tab_id) {
                $(this).find(".close-tab").trigger("click");
            }
        });
    }) : '';

    var divider = $('<li>', {'class': 'divider'});

    var menuBox = $('<div>', {
        'id': menuID,
        'style': 'position:absolute;z-index:2000;',
    });

    var menuHtml = $('<ul>', {
        'aria-controls': id,
        'class': 'dropdown-menu',
        'style': 'cursor:default;min-width:130px;',
        'role': 'menu',
        'aria-url': e.attr('aria-url')
    }).append(refresh)
        .append(remove)
        .append(divider)
        .append(removeOther)
        .append(left)
        .append(right)
        .append(removeAll);

    menuBox.css({
        'top': obj.clientY + 15,
        'left': obj.clientX
    });

    menuBox.addClass('open').append(menuHtml).appendTo('body');

    menuBox.on('mouseleave', function () {
        mouseleaveTimer && clearTimeout(mouseleaveTimer);
        mouseleaveTimer = null;
        isMouseleave = true;
        $(this).fadeOut();
    });
    menuBox.on('mouseenter', function () {
        mouseleaveTimer && clearTimeout(mouseleaveTimer);
        mouseleaveTimer = null;
        isMouseleave = false;
        $(this).show();
    });
    navobj.on('mouseleave', function () {
        mouseleaveTimer && clearTimeout(mouseleaveTimer);
        mouseleaveTimer = null;
        mouseleaveTimer = setTimeout(function() {
            if(isMouseleave === true){
                $('#'+menuID).fadeOut();
            }
        }, 500);
    });

    $(document).on('click', function () {
        $('#'+menuID).remove();
    });
};
options.contextmenu && navobj.on('contextmenu', 'li[role=presentation]', function (e) {
    var id = $(this).children('a').attr('aria-controls');
    _menu(id, $(this), e);
    return false;
});

        //记忆多标签(初始化生成空内容标签) PGCAO
        $.each(addtabs_list, function(id, row){
            _add(row, true);
        });

        /*
        var el;
        $('body').on('dragstart.h5s', '.nav-tabs li', function (e) {
            el = $(this);
            //清除拖动操作携带的数据，否者在部分浏览器上会打开新页面
            if(e.originalEvent && e.originalEvent.dataTransfer
                && 'function' == typeof e.originalEvent.dataTransfer.clearData){
                e.originalEvent.dataTransfer.clearData();
            }
        }).on('dragover.h5s dragenter.h5s drop.h5s', '.nav-tabs li', function (e) {
            if (el == $(this)) return;
            $('.dragBack').removeClass('dragBack');
            $(this).addClass('dragBack');
            //支持前后调整标签顺序
            if (el.index() < $(this).index()) {
                el.insertAfter($(this))
            } else {
                $(this).insertAfter(el)
            }
        }).on('dragend.h5s', '.nav-tabs li', function () {
            $('.dragBack').removeClass('dragBack');
        });
        */
    };

    //刷新Addtabs
    $.fn.refreshAddtabs = function () {
        var navobj = $(this);
        var dropdown = $(".tabdrop", navobj);
        if (dropdown.length === 0) {
            dropdown = $('<li class="dropdown pull-right hide tabdrop"><a class="dropdown-toggle" data-toggle="dropdown" href="javascript:;">' +
                '<i class="glyphicon glyphicon-align-justify"></i>' +
                ' <b class="caret"></b></a><ul class="dropdown-menu"></ul></li>');
            dropdown.prependTo(navobj);
            dropdown.bind('contextmenu',function(e){
                dropdown.find('>a').trigger('click');
                return false;
            });
        }

        //检测是否有下拉样式
        if (navobj.parent().is('.tabs-below')) {
            dropdown.addClass('dropup');
        }

        var collection = 0;
        var maxwidth = navobj.width() - 65;

        var liwidth = 0;
        //检查超过一行的标签页
        var litabs = navobj.append(dropdown.find('li')).find('>li').not('.tabdrop');
        var totalwidth = 0;
        litabs.each(function () {
            totalwidth += $(this).outerWidth(true);
        });
        if (navobj.width() < totalwidth) {
            litabs.each(function () {
                liwidth += $(this).outerWidth(true);
                if (liwidth > maxwidth) {
                    dropdown.find('ul').append($(this));
                    collection++;
                }
            });
            if (collection > 0) {
                dropdown.removeClass('hide');
                if (dropdown.find('.active').length === 1) {
                    dropdown.addClass('active');
                } else {
                    dropdown.removeClass('active');
                }
            }
        } else {
            dropdown.addClass('hide');
        }

    };
})(jQuery);
